package com.module.overview.ui.duringExercise

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.common.base.app.extras.no
import com.common.base.app.viewmodel.BaseViewModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import java.util.Locale

/**
 * 作者：sosou
 * <p>
 * 版本：1.0
 * <p>
 * 创建日期：2025/4/7
 * <p>
 * 描述：
 * <p>
 * 修订历史：
 */
class DuringExerciseViewModel : BaseViewModel() {

    // 计时器状态
    private var isRunning = false
    var seconds = 0L
    var timerJob: Job? = null

    val timeString = MutableLiveData<String>()

    override fun onCleared() {
        timerJob?.cancel()
        super.onCleared()
    }

    /**
     * 开始计时器
     */
    fun startTimer() {
        isRunning.no {
            isRunning = true
            timerJob = viewModelScope.launch {
                while (isActive) {
                    delay(1000) // 延迟1秒
                    seconds++
                    updateTimerText(seconds)
                }
            }
        }
    }

    /**
     * 暂停计时器
     */
    fun pauseTimer() {
        isRunning = false
        timerJob?.cancel()
        timerJob = null
    }

    /**
     * 继续计时器
     */
    fun resumeTimer() {
        startTimer()
    }

    /**
     * 重置计时器
     */
    fun resetTimer() {
        pauseTimer()
        seconds = 0
        updateTimerText(seconds)
    }


    /**
     * 更新计时器文本显示
     */
    fun updateTimerText(mSeconds:Long) {
        val hours = mSeconds / 3600
        val minutes = (mSeconds % 3600) / 60
        val secs = mSeconds % 60
        timeString.value = String.format(Locale.getDefault(), "%02d:%02d:%02d", hours, minutes, secs)
    }

}